/* MailDemo.java 
* Created on Dec 15, 2012 
*@Author: Mr.Viet 
*@Phone: 01683430426 
*@Email: phamvanvietcdhd@gmail.com
*/ 
package com.javamail; 

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.search.FlagTerm;

public class MailDemo {
	
	public MailDemo() {
	}

	public static void main(String[] args) {
		MailDemo m = new MailDemo();
//		m.sendMail();
		m.recevingMail();
	}
	public Session cretateMailSession(){
		Session session = null;
		Properties p = System.getProperties();
		p.put("mail.smtp.host", "smtp.gmail.com");
		p.put("mail.smtp.port", "465");
		p.put("mail.smtp.socketFactory.port", "465");
		p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		p.put("mail.smtp.auth", "true");
		session = Session.getInstance(p, new Authenticator() {
			@Override
			protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
				
				return new javax.mail.PasswordAuthentication("manhcuongbknp@gmail.com", "domanhcuong");
			}
		});
		return session;
	}
	public void sendMail(){
		Session s = this.cretateMailSession();
		//Tao 1 mail de gui di
		Message m = new MimeMessage(s);
		try {
			m.setSubject("Demo Java mail");
			m.setContent("Noi Dung Can Gui","text/html");
			m.setFrom(new InternetAddress("manhcuongbknp@gmail.com","Mr.viet"));
			m.setRecipient(RecipientType.TO, new InternetAddress("phamvanvietcdhd@gmail.com"));
			Transport.send(m);
			System.out.println("ok Da gui");
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
	}
	public void recevingMail(){
		Session s = this.cretateMailSession();
		try {
			Store store = s.getStore("pop3s");
			store.connect("pop.gmail.com","phamvanvietcdhd@gmail.com", "vietbac26391");
			Folder folder =store.getFolder("INBOX");
			folder.open(Folder.READ_ONLY);
			
			FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
			
//			Message[] arrMess = folder.getMessages();
			Message[] arrMess = folder.search(ft);
			for (Message m : arrMess) {
				String subject = m.getSubject();
				System.out.println(subject);
			}
			
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		
	}

}
